#include <REGX52.h>
#include "LCD1602.h"
#include "DS18B20.h"
#include "Delay.h"
#include "Timer.h"
#include "SoleKey_NoHang.h"
#include "AT24C02.h"

float Temp, TShow;
char HTemp, LTemp;
unsigned char KeyNum;

/**
  * @brief		显示温度上下限，改变正负号
  * @parm		无
  * @retval		无
  */
void Show_HLTemp()
{
	if(HTemp >= 0)	LCD_ShowChar(2, 4, '+');
	else	LCD_ShowChar(2, 4, '-');
	LCD_ShowNum(2, 5, HTemp, 3);
	
	if(LTemp >= 0)	LCD_ShowChar(2, 12, '+');
	else	LCD_ShowChar(2, 12, '-');
	LCD_ShowNum(2, 13, LTemp, 3);
}

void main()
{
	DS18B20_ConventT();
	Delayms(1000);
	//读取温度上下限
	HTemp = AT24C02_ReadByte(0x00);
	LTemp = AT24C02_ReadByte(0x01);
	//保证温度上下限合法
	if(HTemp > 125 || LTemp < -55 || HTemp <= LTemp){
		HTemp = 20, LTemp = 15;
	}
	//LCD1602初始化部分
	LCD_Init();
	LCD_ShowString(1, 1, "T:");
	//温度上限
	LCD_ShowString(2, 1, "HT:");
	//温度下限
	LCD_ShowString(2, 9, "LT:");
	Show_HLTemp();
	//初始化时钟
	Timer0_Init();
	
	while(1)
	{
		DS18B20_ConventT();
		Temp = DS18B20_ReadT();
		if(Temp >= 0)
		{
			LCD_ShowChar(1, 3, '+');
			TShow = Temp;
		}
		else
		{
			LCD_ShowChar(1, 3, '-');
			TShow = -Temp;
		}
		LCD_ShowNum(1, 4, TShow, 3);//显示三位整数
		LCD_ShowChar(1, 7, '.');
		LCD_ShowNum(1, 8, (unsigned long)(TShow * 100) % 100, 2);//显示两位小数
		
		//获取按键
		KeyNum = Key();
		if(KeyNum)
		{
			if(KeyNum == 1)//温度上限+1
				HTemp++;
			if(KeyNum == 2)//温度上限-1
				if(HTemp > LTemp + 1)
					HTemp--;
			if(KeyNum == 3)//温度下限+1
				if(HTemp > LTemp + 1)
					LTemp++;
			if(KeyNum == 4)//温度下限-1
				LTemp--;
			//判断合法
			if(HTemp > 125)
				HTemp = 0;
			if(LTemp < -55)
				LTemp = 0;
			//显示上下限
			Show_HLTemp();
			//将温度上下限写入AT24C02
			AT24C02_WriteByte(0x00, HTemp);
			Delayms(5);
			AT24C02_WriteByte(0x01, LTemp);
		}
		if(Temp > HTemp)			//越界判断
			LCD_ShowString(1, 13, "OV:H");
		else if(Temp < LTemp)
			LCD_ShowString(1, 13, "OV:L");
		else
			LCD_ShowString(1,13,"    ");
	}
}

//定时器0中断函数模板
void Timer0_Rountine(void) interrupt 1
{
	static unsigned int KeyCount = 0;
	TH0 = 64535 / 256;		//高8位
	TL0 = 64535 % 256 + 1;		//低8位
	KeyCount++;
	if(KeyCount >= 20)
	{
		KeyCount = 0;
		SoleKey_Looper();
	}
}



